package com.mahiru.mahiruaiagent.app;

import com.mahiru.mahiruaiagent.advisor.MyLoggerAdvisor;
import com.mahiru.mahiruaiagent.rag.ChatAppRagCustomAdvisorFactory;
import com.mahiru.mahiruaiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @Author Enkidu
 * @Date 2025/7/3 23:53
 */
@Slf4j
@Component
public class ChatApp {

    private final ChatClient chatClient;

    public ChatApp(ChatModel dashscopeChatModel) {
        // 基于文件的对话记忆
        // String firedir = System.getProperty("user.dir") + "/tmp/chat-memory";
        // FileBasedChatMemory chatMemory = new FileBasedChatMemory(firedir);
        // 基于内存的对话记忆
        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(ChatSystemPrompt.SYSTEM_PROMPT_MAHIRU)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory)
                        // 自定义日志拦截器
                        , new MyLoggerAdvisor()
                        // 自定义推理增强拦截器
                        // ,new ReReadingAdvisor()
                )
                .build();
    }

    /**
     * AI基础对话
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(
                        spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)
                )
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        // log.info("content:{}", content);
        return content;
    }

    /**
     * AI基础对话 （SSE流式传输）
     *
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId) {

        return chatClient.prompt()
                .user(message)
                .advisors(
                        spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)
                )
                .stream()
                .content();
    }

    record ChatReport(String title, List<String> careList) {
    }

    /**
     * AI 报告（结构化输出）
     *
     * @param message
     * @param chatId
     * @return
     */
    public ChatReport doChatWithReport(String message, String chatId) {

        ChatReport chatReport = chatClient
                .prompt()
                .system(ChatSystemPrompt.SYSTEM_PROMPT_MAHIRU + "每次在对话给出建议后都需要生成对话总结，标题为{用户名}的对话总结，内容为关怀列表")
                .user(message)
                .advisors(
                        spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)

                )
                .call()
                .entity(ChatReport.class);
        log.info("chatReport:{}", chatReport);
        return chatReport;
    }

    // 注入向量数据库
    @Resource
    private VectorStore chatAppVectorStore;

    // 云pg向量知识库
    // @Resource
    // private Advisor chatAppRagCloudAdvisor;

    @Resource
    private VectorStore pgVectorVectorStore;

    @Resource
    private QueryRewriter queryRewriter;

    /**
     * AI 对话增强（RAG）
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message, String chatId) {
        // 对查询进行重写
        // String queryRewrite = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                // 查询重写
                // .user(queryRewrite)
                .advisors(
                        spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)
                )
                // 应用 RAG 知识库问答
                // .advisors(new QuestionAnswerAdvisor(chatAppVectorStore))
                // 应用 RAG 检索增强服务（基于阿里云知识云服务）
                // .advisors((chatAppRagCloudAdvisor))
                // 应用 RAG 检索增强服务（基于 PgVector 向量存储）
                // .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                // 应用 RAG 检索增强服务（ 高级文档检索查询器+ 上下文增强器）
                .advisors(ChatAppRagCustomAdvisorFactory.createChatAppRagCustomAdvisor(chatAppVectorStore, "精通"))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        // log.info("content:{}", content);
        return content;
    }

    // 引入工具类集合
    @Resource
    private ToolCallback[] allTools;

    /**
     * AI 调用工具
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithTools(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(
                        spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)
                )
                .tools(allTools)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        // log.info("content:{}", content);
        return content;
    }

    // Ai调用 MCP 服务
    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    /**
     * AI 调用 MCP 服务
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .system("对于涉及地理位置的查询，请优先使用高德地图工具获取信息。")
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 装入 MCP 服务
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        // log.info("content: {}", content);
        return content;
    }

}
